from pydantic import BaseModel, validator
from typing import Optional
from datetime import datetime, date

class RecordBase(BaseModel):
    phar_ID: int
    con_date: date
    medicine_ID: int
    medicine_name: str
    number: int
    patient_ID: int
    total_price: int

    @validator('number')
    def validate_number(cls, v):
        if v <= 0:
            raise ValueError("药品数量必须大于0")
        return v
    
    @validator('total_price')
    def validate_total_price(cls, v):
        if v <= 0:
            raise ValueError("总价必须大于0")
        return v

class RecordCreate(RecordBase):
    pass

class RecordUpdate(BaseModel):
    phar_ID: Optional[int] = None
    con_date: Optional[date] = None
    medicine_ID: Optional[int] = None
    medicine_name: Optional[str] = None
    number: Optional[int] = None
    patient_ID: Optional[int] = None
    total_price: Optional[int] = None

    @validator('number')
    def validate_number(cls, v):
        if v is not None and v <= 0:
            raise ValueError("药品数量必须大于0")
        return v
    
    @validator('total_price')
    def validate_total_price(cls, v):
        if v is not None and v <= 0:
            raise ValueError("总价必须大于0")
        return v

class RecordResponse(RecordBase):
    ID: int
    dispensed_at: datetime

    class Config:
        from_attributes = True